<template>
  <el-upload
    drag
    multiple
    action="/api/v1/common/upload"
    :headers="headers"
    :data="uploadData"
    :before-upload="beforeUpload"
    :on-success="onSuccess"
    :on-remove="removeFile"
    :on-error="onError"
    :file-list="fileList"
  >
    <i class="el-icon-upload" />
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
  </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'Upload',
  props: {
    uploadData: {
      type: Object,
      default: () => {
        return {
          type: 'sys'
        }
      }
    },
    files: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fileList: [],
      showFileList: []
    }
  },
  computed: {
    headers() {
      return {
        Authorization: getToken()
      }
    }
  },
  watch: {
    files: {
      handler(newval) {
        if (newval && newval.length) {
          console.log('newval', newval)
          this.fileList = newval.map(el => {
            return {
              ...el,
              status: 'success',
              data: {
                ...el
              }
            }
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    beforeUpload(file) {
      // console.log('fo;e', file)
      this.fileList.push({
        ...file,
        name: file.name,
        percentage: 0,
        status: 'uploading'
      })
      // this.fileList.forEach(el => {
      //   if (el.uid === file.uid) {
      //     el.status = 'uploading'
      //   }
      // })
    },
    onSuccess(response, file) {
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid === file.uid) {
          if (response.code === 200) {
            this.fileList[i].data = response.data
            this.fileList[i].status = 'success'
          } else {
            this.fileList[i].status = 'fail'
          }
          break
        }
      }
    },
    onError(err, file) {
      console.log(err, file)
    },
    removeFile(e) {
      console.log(e)
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid === e.uid) {
          this.fileList.splice(i, 1)
          break
        }
      }
    },
    getFiles() {
      console.log('this.fileList')
      if (this.fileList.filter(v => v.status === 'uploading').length) {
        this.$message.warning('文件上传中')
        return false
      } else {
        return this.fileList.filter(v => v.status === 'success').map(el => el.data)
      }
    }
  }
}
</script>

<style scoped>

</style>
